<?php
/**
 * User: xuhong
 * Date: 2018/11/26
 */

namespace App\Services\Fuyou;


use App\Services\Common\HttpCurl;
use App\Services\Common\ZSign;
use App\Services\Common\ZString;
use App\Services\Common\ZXml;

class FuYouConfig
{
    // 接口域名
    public static $api_domain = "https://mchntapi.fuiou.com";

    // 签名使用的key
    public static $sign_key = "12345678901234567890123456789012";

    /**
     * 渠道商户号查询
     * @param $request
     * @return mixed
     * @throws \Exception
     */
    public static function merchantQuery($request)
    {
        $api_type = "merchant";
        // 接口地址
        $url_api = self::$api_domain . "/wxMchntMng.fuiou?action=wxChnlMchntGet";

        var_dump($url_api);

        $param_sign["ins_cd"] = config("app.fuyou_setting.ins_cd");

        // 必填数据
        $param_sign["mchnt_cd"] = $request["mchnt_cd"];
        $param_sign["trace_no"] = $request["trace_no"];

        $response = self::sendRequest($url_api, $param_sign, $api_type);

        return self::afterRequest($response, $api_type);
    }


    /**
     * 微信参数配置
     * @param $request
     * @return mixed
     * @throws \Exception
     */
    public static function wechatSet($request)
    {
        $api_type = "wechat";
        // 接口地址
        $url_api = self::$api_domain . "/wxMchntMng.fuiou?action=xyWechatConfigSet";

        $param_sign["insCd"] = config("app.fuyou_setting.ins_cd");

        // 必填数据
        $param_sign["trace_no"] = $request["trace_no"];
        $param_sign["agencyType"] = $request["agencyType"];

        $param_sign["configs"][] = [
            "mchntCd" => $request["wechat_mchntCd"],
            "subAppid" => $request["wechat_subAppid"],
            "jsapiPath" => $request["wechat_jsapiPath"],
            "subscribeAppid" => $request["wechat_subscribeAppid"]
        ];

        !empty($request["sub_ins_cd"]) ? $param_sign["sub_ins_cd"] = $request["sub_ins_cd"] : false;
        !empty($request["channelFlag"]) ? $param_sign["channelFlag"] = $request["channelFlag"] : false;

        $response = self::sendRequest($url_api, $param_sign, $api_type);

        return self::afterRequest($response, $api_type);
    }

    /**
     * 微信参数查询
     * @param $request
     * @return mixed
     * @throws \Exception
     */
    public static function wechatGet($request)
    {
        $api_type = "wechat";

        $url_api = self::$api_domain . "/wxMchntMng.fuiou?action=xyWechatConfigGet";

        $param_sign["insCd"] = config("app.fuyou_setting.ins_cd");

        // 必填数据
        $param_sign["trace_no"] = $request["trace_no"];
        $param_sign["agencyType"] = $request["agencyType"];

        $param_sign["configs"][] = [
            "mchntCd" => $request["wechat_mchntCd"],
        ];

        !empty($request["sub_ins_cd"]) ? $param_sign["sub_ins_cd"] = $request["sub_ins_cd"] : false;
        !empty($request["channelFlag"]) ? $param_sign["channelFlag"] = $request["channelFlag"] : false;


        $response = self::sendRequest($url_api, $param_sign, $api_type);

        return self::afterRequest($response, $api_type);
    }



    /**
     * 发送请求
     * @param $url
     * @param $param_sign
     * @param $request_type
     * @return mixed
     * @throws \Exception
     */
    public static function sendRequest($url, $param_sign, $request_type)
    {
        $param_api = $param_sign;

        if ($request_type == "merchant") {
            // 排序与合并成字符串
//            $sign = ZString::sortAndCombine($param_sign) . "&key=" . config("app.fuyou_setting.sign_key");
            $sign = ZString::sortAndCombine($param_sign) . "&key=040f23510fbf4b34ae3895272e83c58c";

            var_dump($sign);

            $param_api["sign"] = strtoupper(md5($sign));

            $param_api = "<?xml version=\"1.0\" encoding=\"GBK\" standalone=\"yes\"?><xml>" . ZXml::arrayToXml2($param_api) . "</xml>";


            var_dump($param_api);


            // 经过两次urlencode()之后的字符串
            $param_api = "req=" . urlencode(urlencode($param_api));

        } else {
            // 排序与合并成字符串
            $sign = self::sortAndCombine($param_sign) . "&key=" . config("app.fuyou_setting.sign_key");

            $param_api["sign"] = strtoupper(md5($sign));
            $param_api = "req=" . json_encode($param_api, JSON_UNESCAPED_UNICODE);
        }
        $response = HttpCurl::doPost($url, $param_api);
        return $response;
    }


    /**
     * 返回结果
     * @param $response
     * @param $response_type
     * @return mixed
     * @throws \Exception
     */
    public static function afterRequest($response, $response_type)
    {

        if ($response_type == "merchant") {
            $response = URLdecode($response);
            $response = iconv("GBK", "UTF-8//IGNORE", $response);

            var_dump($response);
            exit;
            $response = str_replace("<?xml version=\"1.0\" encoding=\"GBK\" standalone=\"yes\"?>", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", $response);

            $response = ZXml::xml2array($response);
            if ($response["ret_code"] == "0000") {
                $result["status"] = "1";
                $result["msg"] = "success";
                $result["data"] = $response;
            } else {
                $result["status"] = "0";
                $result["msg"] = $response["ret_msg"];
            }
        } else {
            $response = json_decode($response, true);

            if ($response["retCode"] == "0000") {
                $result["status"] = "1";
                $result["msg"] = "success";
                $result["data"] = $response;
            } else {
                $result["status"] = "0";
                $result["msg"] = $response["retMsg"];
            }
        }
        return $result;
    }


    /**
     * 排序并合并字符串
     * @param $data
     * @return string
     */
    public static function sortAndCombine($data)
    {
        $combineStr = '';
        // 排序
        ksort($data);
        // 处理数据
        foreach ($data as $key => $value) {

            if (is_array($value)) {
                ksort($value[0]);
                $sub_data = json_encode($value, JSON_UNESCAPED_UNICODE);
                $sub_data = str_replace("\"", "", $sub_data);
                $combineStr .= "$key={$sub_data}&";
            } else {
                $combineStr .= "{$key}={$data[$key]}&";
            }
        }

        $combineStr = rtrim($combineStr, "&");
        return $combineStr;
    }
}